300. Routing
Intro to next.js Routing
- Next.js has a file-system based router built on the concept of pages.
- When a file is added to the pages directory, it's automatically available as a route.
- The files inside the pages directory can be used to define most common patterns.
- filenames, nested file structure define routing scheme
Type of Routes
//js files with their respective endpoints to reach them.
- pages
- index.js /
- about.js /about
- profile.js /profile
- blog [nested routes]
- index.js /blog
- my.js /blog/my
- [blog_id].js /blog/{blog_id}
- docs
- [...params].js /catch all routes
- index routes
/
,/blog
- route with pages
/about
,/profile
- nested routes
/blog/my
,
- dynamic routes
- use [] to define dynamic routes
/blog/{blog_id}
- catch-all routes
/docs/python/collections/list
- used to match all request types
- returns an array with request query
//nested dynamic routes
- products
- [product_id]
- index.js /products/{product_id}
- reviews
- [review_id].js /products/{product_id}/review/{review_id}
search urls such as
/profile?user=zack
will forward request to profile.js
Accessing URL Parameters
- in Next.js you can use query object to access both URL
params
andquery
objects in API, SSR, client-side except for SSG/ISR onlyparams
is available
export async function getServerSideProps(context) {
const {params, query} = context;
//given url like `/shop/{product_id}?brand=apple`
console.log(params); //{product_id: 45}
console.log(query); //{product_id: 45, brand: 'apple'}
cosnt {brand} = query;
}
import { useRouter } from 'next/router'
export default () => {
const router = useRouter()
const {post_id} = router.query;
...
}
How to Navigation
Navigation Using Link
- navigation between pages
//navigating between pages
import Link from 'next/link'
<Link href="/about">About Us</Link>
- navigation between dynamic pages
//navigating between dynamic pages
<Link href={`/blog/${encodeURIComponent(blog.id)}`}>
{blog.title}
</Link>
//or
<Link href={{ pathname: '/blog/[id]', query: { id: blog.id }, }}>
{blog.title}
</Link>
encodeURIComponent
== used to keep the path utf-8 compatible.
- replace current page
//replace current url
//navigating between dynamic pages
//instead of adding a new page to stack it replaces the current page
<Link href={`/blog/${encodeURIComponent(blog.id)}`} replace>
{blog.title}
</Link>
Link
should be used for client side navigation only
for external navigation or for server side navigation use plain old<a>
Navigating Programmatically
import { useRouter } from "next/router";
function Home(){
const router = useRouter();
const handleClick = ()=>{
router.push('/blog');
//router.replace('/blog');
}
return <button onclick={handleClick}>Go to blog </button>
}
export default Home;
How to Create Custom 404 Page
- to override the default 404 page, create a file called
404.js
insidepages
folder
import Link from 'next/link'
function PageNotFound() {
return <p> page not found <Link href={"/"}>go home</Link> </p>
}
export default PageNotFound;
Show Loading Progress When Routing
npm i nextjs-progressbar
import NextNProgress from 'nextjs-progressbar';
export default function MyApp({ Component, pageProps }) {
return (
<>
<NextNProgress />
<Component {...pageProps} />;
</>
);
}
Shallow Routing
- shallow-routing
- Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.
- This can be useful to let users bookmark a page, with configuration they made client side,
const changeCategory = (newCat)=>{
router.push('/?counter=10', undefined, { shallow: true })
}